#coding:utf-8

import wx
import wx.aui as aui
import wx.lib.scrolledpanel as scrolled
import customwid as wid
import ico
from report import RecordInfo, RecordConnection
from database import Dbapi
import buss.market as market
import datamethod as dm
import sys, os
from win32com import client


record_info = None


class RecordPanel(scrolled.ScrolledPanel):
    def __init__(self, parent, mark):
        scrolled.ScrolledPanel.__init__(self, parent)
        self.SetBackgroundColour(wx.WHITE)
        
        busstype, bussdata = record_info.getTestCaseData(mark)
        testname = market.findProtocol(dm.str2data(busstype)).getName()
        repeat, patience, rest = record_info.getTestCaseOption(mark)
        
        items = (
                (u"业务名称:", testname),
                (u"业务类型:", busstype),
                (u"业务数据:", bussdata),
                (u"重复次数:", str(repeat)),
                (u"忍耐时间:", str(patience)),
                (u"停留时间:", str(rest)),
                )
        
        datas = record_info.getRecordData(mark)
        cls = market.findRender(busstype)
        if cls:
            self.render = cls(datas)
            panel = self.render.interprete(self)
        else:
            panel = None
        
        btnBackGeneral = wx.Button(self, label = u"返回")
        
        self.mainsizer = wid.Sizer(wx.VERTICAL, flag = wx.ALL|wx.EXPAND, border = 5)
        
        for title, caption in items:
            item = wid.TitleTextLabel(self, title, caption)
            self.mainsizer.Add(item)
            
        self.mainsizer.Add(btnBackGeneral, flag= wx.LEFT|wx.RIGHT, border=5)
        if panel:
            self.mainsizer.Add(panel, proportion=1, border = 10)
        self.SetSizer(self.mainsizer)
        self.SetupScrolling()
        self.Bind(wx.EVT_BUTTON, self.OnBack, btnBackGeneral)
        
    def OnBack(self, evt):
        self.GetParent().SetSelection(0)

    def showPanel(self):
        pass

class GeneralWindow(scrolled.ScrolledPanel):
    def __init__(self, parent):
        scrolled.ScrolledPanel.__init__(self, parent)
        self.SetBackgroundColour(wx.WHITE)
        self.tel = wid.TitleTextLabel(self, u"车辆:", "")
        self.testbegin = wid.TitleTextLabel(self, u"测试开始:", "")
        self.testend = wid.TitleTextLabel(self, u"测试截止:", "")
        
        self.record = wx.ListCtrl(self, style = wx.LC_REPORT)
        self.record.SetFont(wid.Font(8))
        columns = ((u"测试用例", 175),
                   (u"开始时间", 175),
                   (u"结束时间", 175),
                   (u"连发次数", 175),
                   (u"忍耐时间", 175),
                   (u"停留时间", 175),
                   )
        for name, width in columns:
            self.record.InsertColumn(sys.maxint, name, width = width)
        self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnShowRecord, self.record)
        
        
        mainsizer = wid.Sizer(wx.VERTICAL, flag=wx.ALL|wx.EXPAND, border = 5)
        mainsizer.Attach(self.tel, self.testbegin, self.testend, wx.Size(-1,20))
        mainsizer.Add(self.record, proportion = 1)
        self.SetSizer(mainsizer)
        self.Fit()
        
    def setBasicInfo(self, tel, begin, end):
        self.tel.SetLabel(tel)
        self.testbegin.SetLabel(begin)
        self.testend.SetLabel(end)
        
    def OnShowRecord(self, evt):
        self.GetParent().showRecord(evt.GetItem().GetData())
        
    def insertRecord(self, id, begin, end, busstype, bussdata, 
                     repeat, patience, rest):
        buss = market.findProtocol(dm.str2data(busstype))
        testname = u""
        if buss:
            testname = buss.getName()
        item = self.record.InsertStringItem(sys.maxint, testname)
        x = [begin, end, repeat, patience, rest]
        for i in range(len(x)):
            self.record.SetStringItem(item, i+1, str(x[i]))
        self.record.SetItemData(item, self.record.GetItemCount())
        return item

class FunctionPanel(wx.ListCtrl):
    pass


class ReportPanel(aui.AuiNotebook):
    def __init__(self, parent):
        aui.AuiNotebook.__init__(self, parent, style=wx.BORDER_NONE)
        self.SetTabCtrlHeight(0)
        self.mainWindow = GeneralWindow(self)
        self.AddPage(self.mainWindow)
        
    def AddPage(self, control):
        cnt = self.GetPageCount()
        aui.AuiNotebook.AddPage(self, control, str(cnt))
        return cnt
        
    def showReport(self):
        global record_info
        if not record_info: return
        tel, begin, end = record_info.getTestInfo()
        self.mainWindow.setBasicInfo(tel, begin, end)
        for record in record_info.getAllTestCaseInfo():
            self.mainWindow.insertRecord(*record)
            panel = RecordPanel(self, record[0])
            self.AddPage(panel)
                
    def showRecord(self, pageIndex):
        if pageIndex:
            self.SetSelection(pageIndex)
        
            

def readRecord(path):
    global record_info
    if record_info:
        record_info.getConnection().close()
    conn = RecordConnection(path)
    record_info = RecordInfo(conn)
    if record_info.getTestInfo():
        return True
    return False

class ReportForm(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, size=(800,600), title = u"Report")
        self.mgr=aui.AuiManager()
        self.mgr.SetManagedWindow(self)
        
        self.operation = wid.OperationPanel(self, "")
        items = (
                 None,
                 (ico.getBmp("fileopen"), wx.ITEM_NORMAL, u"打开报告", self.OnOpenReport),
                 None,
                 (ico.getBmp("excelone"), wx.ITEM_NORMAL, u"导出当前Excel", self.OnExportCurrentExcel),
                 (ico.getBmp("excelall"), wx.ITEM_NORMAL, u"导出全部Excel", self.OnExportAllExcel),
                 )
        self.operation.layout(items)
        self.mgr.AddPane(self.operation, aui.AuiPaneInfo().Name(u"operation").Top().
                                        ToolbarPane().Floatable(False).MinSize((220,-1)))
        self.view = ReportPanel(self)
        self.mgr.AddPane(self.view, aui.AuiPaneInfo().Name(u"view").
                                        Caption(u"显示").Center().
                                        Floatable(False).MinSize((220,-1)).
                                        CloseButton(False).MaximizeButton(True))
        '''
        self.function = FunctionPanel(self)
        self.mgr.AddPane(self.function, aui.AuiPaneInfo().Name(u"function").
                                        Caption(u"功能").Left().
                                        Floatable(False).MinSize((150,-1)).
                                        CloseButton(False).MaximizeButton(False))
        '''
        self.mgr.Update()
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        
    def showReport(self, filename):
        if not filename: return
        if readRecord(filename):
            self.view.showReport()
        else:
            wx.MessageBox(u"文件格式错误")
        
    def OnOpenReport(self, evt):
        _ReportPath = "datareport"
        try:
            topName, dirnames, filenames = os.walk(_ReportPath).next()
        except StopIteration:
            dirnames = []
        files = []
        
        for dirname in dirnames:
            if os.path.exists(_ReportPath+"/"+dirname+"/.report"):
                
                files.append(unicode(dirname,'gbk'))
        dlg = wx.SingleChoiceDialog(self, u'请选择一个文件', u'选择', files)
        
        if dlg.ShowModal() == wx.ID_OK:
            path = _ReportPath + "/"+ dlg.GetStringSelection()
            try:
                topName, dirnames, filenames = os.walk(path).next()
            except StopIteration:
                dirnames = []
            for dirname in dirnames:
                print path+"/%s/data"%dirname
                self.showReport(path+"/%s/data"%dirname)
        dlg.Destroy()
        
    def OnExportCurrentExcel(self, evt):
        page = self.view.GetPage(self.view.GetSelection())
        if not hasattr(page, 'render'): return
        if hasattr(page.render, 'exportExcel'):
            self.exportExcel([page.render])
        else:
            wx.MessageBox(u"该页暂不能输出Excel文档.")
        
    def OnExportAllExcel(self, evt):
        
        renders = []
        for i in range(1, self.view.GetPageCount()):
            page = self.view.GetPage(i)
            if hasattr(page, 'render') and hasattr(page.render, 'exportExcel'):
                renders.append(page.render)
        self.exportExcel(renders)
        
    def exportExcel(self, renders):
        path = wx.FileSelector(parent = self, wildcard = u"Excel文档(*.xls)|*.xls", 
                               flags=wx.FD_SAVE)
        if not path: return
        xlApp = client.Dispatch('Excel.Application')
        xlBook = xlApp.Workbooks.Add()
        xlApp.Visible = True
        try:
            for render in renders:
                xlSheet = xlBook.WorkSheets.Add()
                try:
                    render.exportExcel(xlSheet)
                except Exception, e:
                    wx.MessageBox(parent = self, message=str(e)) 
                    continue
        finally:
            xlBook.Close(True, path)
            xlApp.Quit()
            
    def OnClose(self, evt):
        global record_info
        if record_info:
            record_info.getConnection().close()
        record_info = None
        evt.Skip()
 
        
class TestFrom(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, size=(400,400))
        panel = wx.Panel(self)
        btn = wx.Button(panel, label= "large", pos=(0,0))
        self.x = wx.Image('photo/13800000000-091214103717.jpg') 
        x = self.x.Scale(100, 100)
        self.t = wx.StaticBitmap(panel, -1, x.ConvertToBitmap(), (33, 33))
        self.Bind(wx.EVT_BUTTON, self.OnButton)
        
    def OnButton(self, evt):
        self.t.SetBitmap(self.x.Scale(200, 200).ConvertToBitmap())
        self.Refresh()
        evt.Skip()

if __name__ == '__main__':
    app = wx.App(0)
    f = ReportForm(None)
    f.Show()
    f.SetSize((800,500))
    app.MainLoop()